package com.cargo.base.utils;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ExcelUtil {
	@SuppressWarnings("deprecation")
	public static Workbook createWorkBook(List<Map<String, Object>> list,String[] keys,String[] columnNames, String path) {
		// 创建excel工作簿
		File excel= new File(path);
		FileInputStream is;
		try {
			is = new FileInputStream(excel);
			HSSFWorkbook wb = new HSSFWorkbook(is);
			HSSFSheet sheet = wb.getSheetAt(0);  //模版的第一行样式
			// 手动设置列宽。第一个参数表示要为第几列设；，第二个参数表示列的宽度，n为列高的像素数。
			for(int i=0;keys!=null && i<keys.length;i++){
				sheet.setColumnWidth((short) i, (short) (35.7 * 150));
			}

			//设置每行每列的值
			for (short i = 1; list!=null && i < list.size(); i++) {
				// Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
				// 创建一行，在页sheet上
				Row row1 = sheet.createRow((short) i);
				// 在row行上创建一个方格
				for(short j=0;keys!=null && j<keys.length;j++){
					Cell cell = row1.createCell(j);
					cell.setCellValue(list.get(i).get(keys[j]) == null?" ": list.get(i).get(keys[j]).toString());
				}
			}
			return wb;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}